const express = require('express')
	  bodyParser = require('body-parser')
	  fs = require('fs')
	  multer = require('multer')
	  cookieParser = require('cookie-parser')
	  app = express()
var fileName
const storage = multer.diskStorage({
	destination:'www/uploads',
	filename:function(req,file,cb){
//		console.log(file)
		var name = req.cookies.username
		var fileType = file.originalname
		var arr = fileType.split('.')
		fileType = arr[arr.length-1]
		fileName = name + '.' + fileType
		cb(null,name + '.' + fileType)
	}
}),
  uploads = multer({storage})
app.use(express.static('www'))
app.use(bodyParser.urlencoded({extended:false}))
app.use(cookieParser())

//用户名验证
app.post('/username',(req,res) => {
	var name = req.body.username
	function send(code,message){
		res.status(200).json({code,message})
	}
	fs.exists(`user/${name}.json`,(ex) => {
		if(ex){
			send('fail','用户名已存在...')
		}
		else{
			send('success','恭喜,用户名可以使用')
		}
	})
})

//用户注册
app.post('/register',(req,res) => {
	req.body.time = new Date()
	req.body.ip = req.ip
	var fileName = `user/${req.body.username}.json`
	fs.exists('user',(ex) => {
		if(ex){
			write()
		}
		else{
			fs.mkdir('user',err => {
				if(err){
					send('fail','抱歉,系统错误,注册失败')
				}
				else{
					write()
				}
			})
		}
	})
	
	function write(){
		fs.writeFile(fileName,JSON.stringify(req.body),err => {
			if(err){
				send('fail','抱歉,系统错误,注册失败')
			}
			else{
				send('success','注册成功')
			}
		})
	}
	function send(code,message){
		res.status(200).json({code,message})
	}
})

//登陆
app.post('/login',(req,res) => {
	fs.exists(`user/${req.body.username}.json`,ex => {
		if(ex){
			fs.readFile(`user/${req.body.username}.json`,(err,data) => {
				if(err){
					send('fail','抱歉,系统错误,请稍后重试')
				}
				else{
					data = JSON.parse(data)
					if(req.body.password == data.password){
//						向服务器发送cookie 此处应加密
						res.cookie('header',data.header)
						res.cookie('username',req.body.username)
						send('success','登陆成功')
					}
					else{
						send('fail','密码错误,请再次确认后进行登录')
					}
				}
			})
		}
		else{
			send('fail','用户名不存在')
		}
	})
	function send(code,message){
		res.status(200).json({code,message})
	}
})

//提交问题
var allQuestions = []
//fs.readFileSync  同步读取文件方式,目的是让其造成阻塞,返回数据,如果成功,则反回读取数据,如果失败则不返回
//fs.existsSync    同步判断文件是否存在的方式,返回true或者false
if(fs.existsSync(`question/questions.json`)){
	var data = fs.readFileSync(`question/questions.json`)
	allQuestions = JSON.parse(data)
}


app.post('/ask',(req,res) => {
//	获取cookie里面的username
		var name = req.cookies.username  //通过cookieParser进行解析的

		if(!name){
			send('fail','请先登录')
		}
		var header = fs.readFileSync(`user/${name}.json`)  //读取提交问题用户对应的账户信息
		header = JSON.parse(header)  //将header序列化为一个对象
		req.body.header = header.header // 将header里面的用户头像信息存储到req.body当中
		// 过滤<>,防止xss攻击
		req.body.content = req.body.content.replace(/</g,'&lt;')
		req.body.content = req.body.content.replace(/>/g,'&gt;')
		req.body.username = name
		req.body.time = new Date()
		req.body.ip = req.ip
		allQuestions.unshift(req.body)
		var fileName = `question/questions.json`
		fs.exists(`question`,ex => {
			if(ex){
				write()
			}
			else{
				fs.mkdir(`question`,err => {
					if(err){
						send('fail','抱歉,系统错误,提交失败')
					}
					else{
						write()
					}
				})
			}
		})
			function write(){
				// console.log(typeof allQuestions)
				fs.writeFile(fileName,JSON.stringify(allQuestions),err => {
					if(err){
						send('fail','抱歉,系统错误,提交失败')
					}
					else{
						send('success','提交成功')
					}
				})
	}
	function send(code,message){
		res.status(200).json({code,message})
	}
		
})

//用户头像
app.post('/header',uploads.single('header'),(req,res) => {
	var name = req.cookies.username
	fs.readFile(`user/${name}.json`,(err,data) => {
		if(err){
			send('fail','头像上传失败')
		}
		else{
			// console.log(data)
			data = JSON.parse(data)
			// console.log(data)
			data.header = fileName
			fs.writeFile(`user/${name}.json`,JSON.stringify(data),err => {
				if(err){
					send('fail','头像上传失败')
				}
				else{
					send('success','头像上传成功')
				}
			})
		}
	})
	function send(code,message){
		res.status(200).json({code,message})
	}
})

// 首页
app.get('/question',(req,res) => {
	res.status(200).send(allQuestions)
})


// 回答问题
app.post('/answer',(req,res) => {
	// 获取到对应问题的下标值
	var index = req.cookies.index
	var data = allQuestions[index]
	var answer = data.answer || []
	var name = req.cookies.username //获取到回答问题用户的用户名
	// var header = fs.readFileSync(`user/${name}.json`)
	// header = header.header   //获取回答用户的头像信息
	var header = req.cookies.header
	var time = new Date()  //用户回答问题的时间
	var content = req.body.answer
	// 将用户回答问题的所有信息封装在一起
	var answer_content = {
		username:name,
		time,
		content,
		header
	}
	answer.push(answer_content) //将用户信息存放在数组中
	data.answer = answer //将数组当中的内容存储到对应的问题对象当中
	fs.writeFile('question/questions.json',JSON.stringify(allQuestions),err => {
		if(err){
			send('fail','对不起，系统出错，请稍后再试')
		}
		else{
			send('success','回答成功')
		}
	})
	function send(code,message){
		res.status(200).json({code,message})
	}
})

app.listen(8080,() => {
	console.log('node is ok')
})
